'''
    @project: Masdevallia
    @author: Austin Baker
    @created: 2/22/2014
    @license: http://opensource.org/licenses/mit-license.php

    The MIT License (MIT)

    Copyright (c) 2014 Austin Baker
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
    About:
    Rig joint data class.
'''

'''
============================================================
--->>   IMPORT MODULES
============================================================
'''
import maya.OpenMaya as OM
import maya.OpenMayaAnim as OMA

import masdevallia.utility.Dag as Dag
import masdevallia.utility.Matrix as Matrix

'''
============================================================
--->>   RIG JOINT CLASS
============================================================
'''
class RigJoint( object ):
    """
    Base class for joints.

    @param inObj: String or MObject. If string then name of existing joint or new joint to create.
    """
    def __new__( cls, inObj ):
        if isinstance( inObj, str ) or isinstance( inObj, OM.MObject ):
            return super( RigJoint, cls ).__new__( cls, inObj )
        else:
            raise RuntimeError( 'RigJoint argument inObj is not a string or MObject. {0}'.format( type( inObj ) ) )
        
    def __init__( self, *args ):
        if len( args ) != 1:
            OM.MGlobal.displayError( '{0} arguments passed. Class takes exactly one'.format( len( args ) ) )
        elif isinstance( args[0], str ) or isinstance( args[0], OM.MObject ):
            # Attributes
            self.name = args[0]
            self.fullname = None
            self.asMObject = None
            self.asDagPath = None
            self.matrixData = None
            
            self.translation = OM.MVector( 0.0, 0.0, 0.0 )
            self.rotation = OM.MEulerRotation( 0.0, 0.0, 0.0 )
            self.scale = [ 1.0, 1.0, 1.0 ]
            self.rotationOrder = 1
            #self.rotationAxis = None
            
            self.drawStyle = 0
            self.radius = 1.0
            self.degreesFreedom = [1, 1, 1]
            self.stiffness = [ 0.0, 0.0, 0.0 ]
            self.preferredAngle = [ 0.0, 0.0, 0.0 ]
            self.jointOrient = OM.MEulerRotation( 0.0, 0.0, 0.0 )
            
            self.updateClassAttributes()
        else:
            OM.MGlobal.displayError( 'RigJoint argument inObj is not a string or MObject. {0}'.format( type( args[0] ) ) )
    
    def updateClassAttributes( self ):
        """
        Fills the class attributes. Only applicable if the joint already exists.
        """
        if Dag.objExists( self.name ):            
            # Node attributes.
            self.fullname = Dag.getPathname( self.name, inFull=True )
            self.asMObject = Dag.getMObject( self.name )
            self.asDagPath = Dag.getDagPath( self.name )
            self.matrixData = Matrix.Matrix( self.fullname, 'worldMatrix' )
            
            # Transform attributes.
            self.translation = self.matrixData.getTranslation()
            self.rotation = self.matrixData.getRotation( OM.MEulerRotation )
            self.scale = self.matrixData.getScale()
            self.rotationOrder = self.matrixData.rotationOrder()            
            
            # Joint attributes.                        
            self.drawStyle = Dag.getPlugByName( self.asMObject, 'drawStyle' ).asInt()
            self.radius = Dag.getPlugByName( self.asMObject, 'radius' ).asDouble()
                        
            jointFn = OMA.MFnIkJoint( self.asMObject )
            
            degreesFreedomPtrs = self.getDegreesFreedomPtrs()
            jointFn.getDegreesOfFreedom( degreesFreedomPtrs[0][0], degreesFreedomPtrs[1][0], degreesFreedomPtrs[2][0] )
            self.degreesFreedom = []            
            for axis in degreesFreedomPtrs:
                self.degreesFreedom.append( OM.MScriptUtil().getBool( axis[0] ) )

            stiffnessPtrs = self.getDoublePtrs()
            jointFn.getStiffness( stiffnessPtrs[0] )
            self.stiffness = [OM.MScriptUtil().getDoubleArrayItem( stiffnessPtrs[0], 0 ),
                              OM.MScriptUtil().getDoubleArrayItem( stiffnessPtrs[0], 1 ),
                              OM.MScriptUtil().getDoubleArrayItem( stiffnessPtrs[0], 2 )]
            
            preferredAnglePtrs = self.getDoublePtrs()
            jointFn.getPreferedAngle( preferredAnglePtrs[0] )
            self.preferredAngle = [OM.MScriptUtil().getDoubleArrayItem( preferredAnglePtrs[0], 0 ),
                                   OM.MScriptUtil().getDoubleArrayItem( preferredAnglePtrs[0], 1 ),
                                   OM.MScriptUtil().getDoubleArrayItem( preferredAnglePtrs[0], 2 )]
            
            self.jointOrient = OM.MEulerRotation()
            jointFn.getOrientation( self.jointOrient )
        
    def getDegreesFreedomPtrs( self ):
        """
        Create pointers used to retrive the joint's degrees of freedom values.
        
        @return: List of Lists. Bool pointer and MScriptUtil pairings.
        """
        x_util = OM.MScriptUtil(1)
        x_ptr = x_util.asBoolPtr()
        y_util = OM.MScriptUtil(1)
        y_ptr = y_util.asBoolPtr()
        z_util = OM.MScriptUtil(1)
        z_ptr = z_util.asBoolPtr()
        return [ ( x_ptr, x_util ), ( y_ptr, y_util ), ( z_ptr, z_util ) ]
        
    def getDoublePtrs( self ):
        """
        Create double pointer.
        
        @return: List of pointer/MScriptUtil pairing.
        """
        util = OM.MScriptUtil()
        util.createFromDouble(0.0, 0.0, 0.0)
        ptr = util.asDoublePtr()
        return [ ptr, util ]
        
    def build( self ):
        """
        Builds the joint. Applies the joint classes attributes to the newly created
        joint node. Create the joint class then set all the class attributes to the
        desired values and finally, build the new joint.
        """
        if Dag.objExists( self.name ):
            OM.MGlobal.displayInfo( 'RigJoint.build() aborted. Joint already exists.' )
        else:
            joint = Dag.createNode( inNodeType='joint' )

            depFn = OM.MFnDependencyNode( joint )
            depFn.setName( self.name )

            self.name = Dag.getPathname( joint, inFull=False )
            self.fullname = Dag.getPathname( joint, inFull=True )
            self.asMObject = Dag.getMObject( self.name )
            self.asDagPath = Dag.getDagPath( self.name )
            self.matrixData = Matrix.Matrix( self.fullname, 'worldMatrix' )

            if self.translation:
                self.matrixData.setTranslation( self.translation )
            
            if self.rotation:
                self.matrixData.setRotation( self.rotation )
                
            if self.scale:
                self.matrixData.setScale( self.scale )
            
            if self.rotationOrder:
                self.matrixData.setRotationOrder( inRotOrder=self.rotationOrder )

            if self.drawStyle:
                plug = Dag.getPlugByName( self.asMObject, 'drawStyle' )
                Dag.setPlugValue( plug, self.drawStyle )

            if self.radius:
                plug = Dag.getPlugByName( self.asMObject, 'radius' )
                Dag.setPlugValue( plug, self.radius )

            if self.degreesFreedom:               
                x_plug = Dag.getPlugByName( self.asMObject, 'jointTypeX' )
                y_plug = Dag.getPlugByName( self.asMObject, 'jointTypeY' )
                z_plug = Dag.getPlugByName( self.asMObject, 'jointTypeZ' )
                Dag.setPlugValue( x_plug, bool( self.degreesFreedom[0] ) )
                Dag.setPlugValue( y_plug, bool( self.degreesFreedom[1] ) )
                Dag.setPlugValue( z_plug, bool( self.degreesFreedom[2] ) )
                
            if self.stiffness:
                x_plug = Dag.getPlugByName( self.asMObject, 'stiffnessX' )
                y_plug = Dag.getPlugByName( self.asMObject, 'stiffnessY' )
                z_plug = Dag.getPlugByName( self.asMObject, 'stiffnessZ' )
                Dag.setPlugValue( x_plug, self.stiffness[0] )
                Dag.setPlugValue( y_plug, self.stiffness[1] )
                Dag.setPlugValue( z_plug, self.stiffness[2] )
                
            if self.preferredAngle:
                x_plug = Dag.getPlugByName( self.asMObject, 'preferredAngleX' )
                y_plug = Dag.getPlugByName( self.asMObject, 'preferredAngleY' )
                z_plug = Dag.getPlugByName( self.asMObject, 'preferredAngleZ' )
                Dag.setPlugValue( x_plug, self.preferredAngle[0] )
                Dag.setPlugValue( y_plug, self.preferredAngle[1] )
                Dag.setPlugValue( z_plug, self.preferredAngle[2] )
                
            if self.jointOrient:
                x_plug = Dag.getPlugByName( self.asMObject, 'jointOrientX' )
                y_plug = Dag.getPlugByName( self.asMObject, 'jointOrientY' )
                z_plug = Dag.getPlugByName( self.asMObject, 'jointOrientZ' )
                Dag.setPlugValue( x_plug, self.jointOrient[0] )
                Dag.setPlugValue( y_plug, self.jointOrient[1] )
                Dag.setPlugValue( z_plug, self.jointOrient[2] )